package com.cloud.commons.utils.wechat;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.cloud.model.entity.accesstoken.AccessToken;
import com.cloud.model.entity.wxmintemplateproject.WxMinTemplateProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class WeixinUtil {

    private static final Logger LOG = LoggerFactory.getLogger(WeixinUtil.class);

    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";


    public static String APPID;
    @Value("${wxMinProject.appId}")
    public void setAppId(String APPID) {
        this.APPID = APPID;
    }

    public static String APPSECRET;
    @Value("${wxMinProject.appSecret}")
    public void setAppsecret(String APPSECRET) {
        this.APPSECRET = APPSECRET;
    }



    /**
     * 获取token
     * @return
     */
    public static AccessToken getAccessToken() {
        AccessToken accessToken = null;
        String requestUrl = access_token_url.replace("APPID", APPID).replace(
                "APPSECRET", APPSECRET);


        JSONObject jsonObject = HttpUtil.httpRequest(requestUrl, "GET", null);

        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                System.out.println(e.getMessage());

            }
        }
        return accessToken;
    }

    /**
     * 通过code获取到用户的openId
     * @param code
     * @return
     */
    public static String code2Session(String code) {
        LOG.info("app_id:" + APPID + "app_secret:" + APPSECRET);
        String code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+ APPID +"&secret="+APPSECRET+"&js_code="+code+"&grant_type=authorization_code";

        LOG.info("request url:" + code2SessionUrl);

        JSONObject jsonObject = HttpUtil.httpRequest(code2SessionUrl,"GET",null);

        LOG.info("request data:" + JSON.toJSONString(jsonObject));

        String openId = "";

        if (ObjectUtils.isEmpty(jsonObject)) {
            throw  new NullPointerException("获取openId失败");
        }

        // 可以获取到数据啦
        try{
            openId = jsonObject.getString("openid");
        }catch (JSONException e) {
            throw new NullPointerException("获取openId失败");
        }
        LOG.info("openId获取成功");
        return openId;
    }


    /**
     * 小程序推送模板消息
     * @param accessToken
     * @param params
     * @return
     */
    public static String sendMiniProgramTemplate(String accessToken, JSONObject params) throws Exception {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        String result = HttpUtil.sendHttpPost(requestUrl, params);
        return result;
    }

    /**
     * 生成小程序推送模板消息所需传递的 json 数据
     * @param wxMinTemplateProject
     * @return
     */
    public static JSONObject setMiniProgramTemplateData(WxMinTemplateProject wxMinTemplateProject) {
        JSONObject resultJson = new JSONObject();
        resultJson.put("touser", wxMinTemplateProject.getOpenId());
        resultJson.put("template_id", wxMinTemplateProject.getTemplateId());
        if (!StringUtils.isEmpty(wxMinTemplateProject.getPage())) {
            resultJson.put("page", wxMinTemplateProject.getPage());
        }

        List<String> keywordValues = wxMinTemplateProject.getKeywordData();
        JSONObject templateMessageData = new JSONObject();
        String templateId = wxMinTemplateProject.getTemplateId();
        if (templateId.equals("nlD1JNUEtWlHjUiqcNFOYJQBG-akvOSbST0b0aWllOs")) {
            // 记账成功提醒
            for (int i = 0; i< keywordValues.size();i++) {
                JSONObject valueObject = new JSONObject();
                valueObject.put("value",keywordValues.get(i));
                String keyword = "";
                switch (i) {
                    case 0:
                        keyword = "time" + (i + 1);
                        break;
                    case 1:
                        keyword = "phrase" + (i + 1);
                        break;
                    case 2:
                        keyword = "amount" + (i + 1);
                        break;
                    case 3:
                        keyword = "name" + (i + 1);
                        break;
                    case 4:
                        keyword = "thing" + (i + 1);
                        break;
                }
                templateMessageData.put(keyword,valueObject);
            }
        } else if (templateId.equals("9idG4F8CNOaiGOo5EYwqB4wxVx8QXtoSg1HjNMnlM4M")){
            // 记账预算提醒
            for (int i = 0; i< keywordValues.size();i++) {
                JSONObject valueObject = new JSONObject();
                valueObject.put("value",keywordValues.get(i));
                String keyword = "";
                switch (i) {
                    case 0:
                        keyword = "time" + (i + 1);
                        break;
                    case 1:
                        keyword = "phrase" + (i + 1);
                        break;
                    case 2:
                        keyword = "amount" + (i + 1);
                        break;
                    case 3:
                        keyword = "thing" + (i + 1);
                        break;
                }
                templateMessageData.put(keyword,valueObject);
            }
        } else if (templateId.equals("e5WNxg6ppcab2LvQTHVPutAlb6BJYAzheIkauWkWS1Q")) {
            // 版本更新通知
            for (int i = 0; i< keywordValues.size();i++) {
                JSONObject valueObject = new JSONObject();
                valueObject.put("value",keywordValues.get(i));
                String keyword = "";
                switch (i) {
                    case 0:
                        keyword = "character_string" + (i + 1);
                        break;
                    case 1:
                        keyword = "thing" + (i + 1);
                        break;
                }
                templateMessageData.put(keyword,valueObject);
            }
        } else {
            throw new RuntimeException("匹配不到有效的订阅id");
        }

        resultJson.put("data", templateMessageData);

        return resultJson;
    }


}
